package com.tieshan.smartwindow.other

import android.app.ActivityManager
import android.content.Context
import android.os.Debug
import com.tieshan.smartwindow.BuildConfig
import com.tieshan.smartwindow.app.AppApplication

object MemoryUtils {

    fun appMemoryInfo(): AppMemory?{
        if(BuildConfig.DEBUG){
            val memoryInfo = Debug.MemoryInfo()
            Debug.getMemoryInfo(memoryInfo)

            val dalvikPss = memoryInfo.dalvikPss // Dalvik (Java heap) 内存，单位为 KB
            val nativePss = memoryInfo.nativePss // Native 内存，单位为 KB
            val totalPss = memoryInfo.totalPss   // 应用总内存占用，单位为 KB
            return AppMemory(dalvikPss, nativePss, totalPss)
        }
        return null
    }

    fun systemMemory(): SysMemory?{
        val activityManager = (AppApplication.app?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)?:return null
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        val total = memoryInfo.totalMem / 1024
        val availMem = memoryInfo.availMem / 1024
        val lowMemory = memoryInfo.lowMemory
        return SysMemory(total.toInt(),availMem.toInt(),lowMemory)

    }

    fun runMemory(): RunMemory {
        val runtime = Runtime.getRuntime()
        val usedMemInKB = (runtime.totalMemory() - runtime.freeMemory()) / 1024
        val maxHeapSizeInKB = runtime.maxMemory() / 1024
        return RunMemory(usedMemInKB.toInt(),maxHeapSizeInKB.toInt())
    }

    data class AppMemory(val dalvikPss:Int,val nativePss:Int,val totalPss:Int)
    data class SysMemory(val total:Int,val available:Int,val lowMemory:Boolean)
    data class RunMemory(val used:Int,val maxHeap:Int)

}